package com.thd.springboottest.sse.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
// http://127.0.0.1:8899/thd/customServlet
//@WebServlet(urlPatterns = "/customServlet")
@WebServlet(value = "/sseServlet")
public class SseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req,resp);
        System.out.println("enter get method");
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        System.out.println("enter post method");
//        Enumeration enu=req.getParameterNames();
//        while(enu.hasMoreElements()){
//            String paraName=(String)enu.nextElement();
//            System.out.println(paraName+": "+req.getParameter(paraName));
//        }
//        //输出 Hello Servlet 到页面
//        resp.getWriter().write("Hello Servlet");
//        //重定向到 baidu
////        resp.sendRedirect("http://www.baidu.com");


        resp.setContentType("text/event-stream;charset=utf-8");
        PrintWriter out = resp.getWriter();
        for (int i = 0; i < 10; i++) {
            out.write("data: 江南一点雨:" + i+"\n\n");
            out.flush();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }



        for (int i = 0; i < 10; i++) {
            out.write("event:customEvt\n");
            out.write("data: " + i +" (customEvt data) \n\n");
            out.flush();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }



    }

//    @Override
//    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.service(req, resp);
//    }
}

